<template>
  <div style="padding: 10px; display: flex; flex-direction: column; height: 100%;">
    <!-- 添加巡视路线对话框 -->
    <el-form ref="patrolRouteFormRef" :model="form" :rules="rules" label-width="100px" style="height: calc(100% - 50px); display: flex; flex-direction: column;">
      <el-form-item label="路线名称" prop="patrolRouteName">
        <el-input v-model="form.patrolRouteName" placeholder="请输入路线名称" />
      </el-form-item>
      <el-form-item label="路线描述" prop="patrolRouteDesc">
        <el-input v-model="form.patrolRouteDesc" placeholder="请输入路线描述" />
      </el-form-item>
      <el-form-item label="调用摄像头" prop="cameraIdList" class="select-camera-form-item">
        <el-button style="position: relative; left: 360px; margin-bottom: 10px;" type="primary" plain @click="openAddDevice">选择</el-button>

        <el-table :data="selectedEquipmentList" border style="flex: 1; ">
          <el-table-column label="设备名称" align="center" prop="equipmentName" min-width="150px" show-overflow-tooltip />
          <el-table-column label="设备识别码" align="center" prop="deviceId" min-width="150px" show-overflow-tooltip />
          <el-table-column label="连接状态" align="center" width="100px">
            <template #default="scope">
              <dict-tag :options="equipment_online_status" :value="scope.row.deviceStatus" />
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="100px" fixed="right">
            <template #default="scope">
              <el-button link type="primary" @click="()=> { deleteDevice(scope.row.equipmentId) }">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
    </el-form>
    <div style="height: 50px; display: flex; justify-content: center; align-items: center;">
      <el-button :loading="buttonLoading" :disabled="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button :loading="buttonLoading" :disabled="buttonLoading" @click="emit('close')">取 消</el-button>
    </div>

    <DeviceSelect ref="deviceSelectRef" :disable-check="false" :data-source="2" :data="form.cameraIdList" @confirm-call-back="selectDevice"></DeviceSelect>
  </div>
</template>

<script setup  lang="ts">
import { addpatrolroute } from '@/api/security/video-patrol/camera-patrol-route';
import { patrolrouteVO } from '@/api/security/video-patrol/camera-patrol-route/types';
import request from '@/utils/request';
import DeviceSelect from '@/components/DeviceSelect/index.vue'

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { equipment_status, equipment_online_status } = toRefs<any>(proxy?.useDict('equipment_status', 'equipment_online_status'));
const buttonLoading = ref(false);
const loading = ref(true);
const total = ref(0);
const selectedEquipmentList = ref([]);
const lockTableSelectionChange = ref(false);
const multipleTableRef = ref<any>();

const patrolRouteFormRef = ref<ElFormInstance>();

const data = reactive<any>({
  form: {
    cameraPatrolRouteId: undefined,
    patrolRouteName: undefined,
    patrolRouteDesc: undefined,
    cameraIdList: undefined,
    equipmentIotFlag: '1'
  },
  queryParams: {
    pageNum: 1,
    pageSize: 20,
    patrolRouteName: undefined,
    patrolRouteDesc: undefined,
    params: {}
  },
  rules: {
    cameraPatrolRouteId: [
      { required: true, message: '主键不能为空', trigger: 'blur' }
    ],
    patrolRouteName: [
      { required: true, message: '路线名称不能为空', trigger: 'blur' }
    ],
    cameraIdList: [
      { required: true, message: '调用摄像头不能为空', trigger: 'blur' }
    ]
  }
});
const { queryParams, form, rules } = toRefs(data);

const emit = defineEmits(['close', 'success']);
const props = defineProps({});

/** 摄像头下拉树 */
let cameraList = ref<patrolrouteVO[]>([]);
const getCameraList = async () => {
  loading.value = true;
  lockTableSelectionChange.value = true; // 锁定多选框选中数据
  await request({
    url: '/equipment/equipment-info/list',
    method: 'get',
    params: { dataSource: 2, ...queryParams.value }
  }).then((res) => {
    cameraList.value = res.rows;
    total.value = res.total;

    // 解锁多选框选中数据
    lockTableSelectionChange.value = false;
  }).finally(() => { loading.value = false; });

  await nextTick(() => {
    cameraList.value.forEach((equipment: any) => {
      selectedEquipmentList.value.forEach(selectedEquipment => {
        if (selectedEquipment.equipmentId == equipment.equipmentId) {
          multipleTableRef.value!.toggleRowSelection(equipment, undefined, false)
        }
      });
    })
  });
};

/**
 * 打开选择设备弹框
 */
const deviceSelectRef = ref<any>();
const openAddDevice = () => {
  deviceSelectRef.value.open();
}

/**
 * 选择设备
 */
const selectDevice = (data: any[]) => {
  selectedEquipmentList.value = data
  form.value.cameraIdList = selectedEquipmentList.value.map(item => { return item.equipmentId });
};

/**
 * 删除设备
 */
const deleteDevice = (equipmentId: any) => {
  selectedEquipmentList.value = selectedEquipmentList.value.filter((item: any) => { return item.equipmentId != equipmentId })
  form.value.cameraIdList = selectedEquipmentList.value.map(item => { return item.equipmentId });
};

/** 提交按钮 */
const submitForm = () => {
  if (selectedEquipmentList.value.length === 0) {
    proxy?.$modal.msgError('请选择设备');
    return;
  }
  form.value.cameraIdList = selectedEquipmentList.value.map(item => { return item.equipmentId });
  patrolRouteFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      await addpatrolroute(form.value).finally(() => buttonLoading.value = false);
      proxy?.$modal.msgSuccess('操作成功');
      emit('close');
      emit('success');
    }
  });
};

onMounted(() => {
  getCameraList();
});
</script>
<style lang="scss" scoped>
:deep(.select-camera-form-item) {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow-y: hidden;
  .el-form-item__content {
    height: calc(100% - 40px);
    display: flex;
    flex-direction: column;
  }
}
</style>
